package com.stone.im.geteway.tcp;

import io.netty.channel.socket.SocketChannel;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理netty长连接的组件
 */
public class SessionManager {

    /**
     * 内部类单例模式
     */
    static class Singleton{
        static SessionManager instance = new SessionManager();
    }

    /**
     * uid到客户端连接得映射
     */
    public ConcurrentHashMap<String, SocketChannel> sessions = new ConcurrentHashMap<String, SocketChannel>();

    /**
     * 存储channel到uid得映射
     */
    public ConcurrentHashMap<String,String> channel2uid = new ConcurrentHashMap<String, String>();

    private ConcurrentHashMap<String,String> channelId2uid = new ConcurrentHashMap<>();

    public String getUidByChannelId(String channelId){
        return channel2uid.get(channelId);
    }

    /**
     * 添加一个建立好连接得客户端
     * @param key
     * @param channel
     */
    public void addClient(String key, SocketChannel channel) {
        String channelId = channel.remoteAddress().getHostName() + ":" + channel.remoteAddress().getPort();
        channel2uid.put(channelId,key);
        sessions.put(key, channel);

        System.out.println("设置本地session"+sessions);
    }

    /**
     * 获取实例
     * @return
     */
    public static SessionManager getInstance() {
        return Singleton.instance;
    }

    /**
     * 判断是否存在某个客户端
     * @param key
     * @return
     */
    public Boolean existClient(String key) {
        return sessions.containsKey(key);
    }

    /**
     * 获取某个用户的连接
     * @param key
     * @return
     */
    public SocketChannel getClient(String key) {
        return sessions.get(key);
    }

    /**
     * 删除某个用户连接
     * @param channel
     */
    public void removeClient(SocketChannel channel){
        String channelId = channel.remoteAddress().getHostName() + ":" + channel.remoteAddress().getPort();
        channel2uid.remove(channel.id().asLongText());
        sessions.remove(channelId);
    }

}
